﻿module RPG {
    export class Portal extends Phaser.Sprite {
        map: Phaser.Tilemap;
        collisionGroup: Phaser.TilemapLayer[];

        constructor(game: Phaser.Game, x: number, y: number, name: string, map: Phaser.Tilemap, collisionGroup:Phaser.TilemapLayer[]) {
            super(game, x, y, name, 0);
            this.anchor.setTo(0.5, 0);

            this.animations.add('fluctuate', null, 12, true);
            this.animations.play('fluctuate');

            this.game.physics.enable(this, Phaser.Physics.ARCADE);
            this.game.physics.arcade.enableBody(this);

            this.body.allowGravity = false;
            this.body.immovable = true;

            this.map = map;
            this.collisionGroup = collisionGroup;
        }

        update() {
            for (var i = 0; i < this.collisionGroup.length; i++) {
                //this.game.physics.arcade.overlap(this, this.collisionGroup[i], RPG.portalOverlap, null, this);
            }
        }
    }

    export function portalOverlap(sprite: Phaser.Sprite, layer: Phaser.Group) {
        sprite.kill();
        console.log('KILLED');
    }

    export function createRandomPortals(game: Phaser.Game, map: Phaser.Tilemap, collisionGroup: Phaser.TilemapLayer[], probability?: number) {
        if (probability == null) {
            probability = 0.25;
        }

        var randNumber;
        var x, y;
        var total = 0;
        for (var i = 0; i < game.world.width - 32; i += 32) {
            randNumber = Math.random();
            if (Math.random() <= probability) {
                x = i;
                y = Math.round(Math.random() * (game.world.height - 32)) + 1;

                var sprite = new RPG.Portal(game, x, y, 'Portal', map, collisionGroup);

                game.add.existing(sprite);
                total++;
            }
        }
        console.log('Total Sprites: ' + total);

    }
} 
